import Vue from 'vue';
import VueRouter from 'vue-router';
import { LoadingBar } from 'iview';
import routes from './routes';
import auth from '@/utils/auth';

Vue.use(VueRouter);

// 路由配置
const router = new VueRouter({
  base: __dirname,
  routes: routes
});

router.beforeEach((to, from, next) => {
  LoadingBar.start();

  let token = auth.getToken();
  if(token && to.name === 'login') {
    next({name: 'homeIndex'});
  } else if(token && to.name !== 'login') {
    next();
  } else if(!token && to.name !== 'login') {
    next({name: 'login'});
  } else if(['login'].indexOf(to.name) !== -1) {
    next();
  } else {
    next({name: 'login'});
  }
});

router.afterEach(() => {
  LoadingBar.finish();
  window.scrollTo(0, 0);
});

export default router;
